package com.eoner.managerlibrary.netsign.version1;

import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.application.BaseApplication;
import com.eoner.common.config.Config;
import com.eoner.baselibrary.utils.CookieNewUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.managerlibrary.user.UserDataManager;

import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 作者：sean
 * 创建时间：2017/7/13 17:25
 * 功能说明：添加请求头
 */

public class HttpInterceptor implements Interceptor {

    private Map<String, Boolean> requestMap = new HashMap<>();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        try {
            if (!isRequesting(request.url().toString())) {
                requestMap.put(request.url().toString(), true);
                Request.Builder builder = request.newBuilder();
                builder.addHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
                builder.addHeader("cookie", CookieNewUtil.getCookie(BaseApplication.getContext()));
                builder.removeHeader("User-Agent");
                builder.addHeader("User-Agent", "android_app_" + CookieNewUtil.getVersionName(BaseApplication.getContext()));
                builder.addHeader("x-token", SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN));
                response = chain.proceed(builder.build());

                ResponseBody responseBody = response.body();
                if (!request.url().toString().contains(".apk")) {
                    BufferedSource source = responseBody.source();
                    source.request(Long.MAX_VALUE);
                    Buffer buffer = source.buffer();
                    Charset UTF8 = Charset.forName("UTF-8");
                    String data = buffer.clone().readString(UTF8);
                    if (data != null && data.startsWith("{")) {
                        JSONObject data1 = new JSONObject(data);
                        if (data1.has("args") && data1.getJSONObject("args") != null) {
                            String level = data1.getJSONObject("args").getString("level");
                            UserDataManager.getInstance().updateUserLevel(level);
                            String inviteCode = data1.getJSONObject("args").getString("invite_code");
                            UserDataManager.getInstance().updateInviteCode(inviteCode);
                        }
                        if ("2".equals(data1.getString("code")) || "1101".equals(data1.getString("code")) || "10000".equals(data1.getString("code"))) {
                            if (SPUtils.getInstance() != null) {
                                SPUtils.getInstance().remove(Config.TASK_TIME_SHARE_GOODS);
                            }
                            //TODO:清除用户信息
                            UserDataManager.getInstance().clearLoginInfo();
                            if (BaseApplication.getContext() != null) {
                                //TODO:跳转主页
                                UtilActivity.finishStartNum(0, UtilActivity.getActivitySize());
                                //TODO:通过路由跳转
                                ARouter.getInstance().build(AroutePath.MAIN_ACTIVITY).withString("code", "1101").navigation();
                            }
                        }
                    }
                }
            }
            requestMap.put(request.url().toString(),false);
        } catch (Exception e) {
            e.printStackTrace();
            requestMap.put(request.url().toString(),false);
        }
        return response;
    }

    private boolean isRequesting(String currentUrl) {
        if (!TextUtils.isEmpty(currentUrl)) {
            if (requestMap.containsKey(currentUrl)) {
                return requestMap.get(currentUrl);
            }
        }
        return false;
    }
}

